<template>
  <div class="app_main">
    <div class="header">用印申请</div>
    <div class="table_body">
      <el-form ref="cuForm" v-loading="formLoading" :rules="cuRules" :model="cuForm" label-width="100px" center
               :disabled="formDisabled"
      >
        <table class="mailTable">
          <tr class="firstTr">
            <td class="column firstTd title">
              <span class="tip">*</span>申请部门
            </td>
            <td class="column">
              {{ main_dept_name }}
            </td>
            <td class="column firstTd title">
              <span class="tip">*</span>申请人
            </td>
            <td class="column">
              {{ user_name }}
            </td>
            <td class="column firstTd title">
              <span class="tip">*</span>职务
            </td>
            <td class="column">
              {{ main_dept_post }}
            </td>
          </tr>
          <tr class="firstTr">
            <td class="column firstTd title" colspan="2">
              <span class="tip">*</span>公司
            </td>
            <td colspan="4">
              <div class="form_item">
                <el-form-item prop="company_id" style="margin-bottom: 0">
                  <el-select v-model="cuForm.company_id" placeholder="请选择公司" @change="initSealTypeList(true)"
                             style="width: 100%"
                  >
                    <el-option v-for="item in companyArr" :key="item.id" :label="item.head" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
            </td>
          </tr>
          <tr class="firstTr">
            <td class="column firstTd title" colspan="2">
              <span class="tip">*</span>印章类型
            </td>
            <td colspan="4">
              <div class="form_item">
                <el-form-item prop="seal_type_id" style="margin-bottom: 0">
                  <el-radio-group v-model="cuForm.seal_type_id" v-show="sealTypeList.length>0">
                    <span v-for="item in sealTypeList">
                      <el-tooltip class="item" effect="dark" content="印章暂未归还" placement="top-start"
                                  v-if="item.disabled"
                      >
                        <el-radio :label="item.id" :key="item.id" :disabled="item.disabled">
                          {{ item.name }}
                        </el-radio>
                      </el-tooltip>
                      <el-radio :label="item.id" :key="item.id" :disabled="item.disabled" v-else>
                        {{ item.name }}
                      </el-radio>
                    </span>
                  </el-radio-group>
                  <div v-show="sealTypeList.length == 0">
                    请先选择公司
                  </div>
                </el-form-item>
              </div>
            </td>
          </tr>
          <tr class="firstTr">
            <td class="column firstTd title" colspan="2">
              <span class="tip">*</span>印章用途
            </td>
            <td colspan="4">
              <div class="form_item">
                <el-form-item prop="purpose" style="margin: 10px 0">
                  <el-input clearable type="textarea" v-model.trim="cuForm.purpose" :rows="4" show-word-limit
                            placeholder="请输入印章用途"
                  ></el-input>
                </el-form-item>
              </div>
            </td>
          </tr>
          <tr class="firstTr">
            <td class="column firstTd title" colspan="2">
              附件
            </td>
            <td class="column" colspan="4" style="text-align: left;padding: 10px 10px 10px 20px">
              <el-upload
                :class="formDisabled?'upload_none':''"
                :action="upFileUrl"
                :headers="uploadHeaders"
                :on-preview="handlePreview"
                :before-remove="beforeRemove"
                :on-remove="onRemove"
                :on-success="uploadSuccess"
                :on-error="uploadError"
                :before-upload="beforeUpload"
                multiple
                :file-list="cuForm.useSealFlowAttachmentList"
              >
                <el-button v-if="!formDisabled" size="small" type="primary">上传附件
                </el-button>
              </el-upload>
            </td>
          </tr>
        </table>
      </el-form>
      <FlowBtnRow :form-name="'cuForm'" :is-new-data="is_created" :can-check="cuForm.can_check"
                  :is-applyer="cuForm.applicant_id == user_id" :flow-status="cuForm.flow_status"
                  @save="save" @submit="submit" @pass="pass" @returnBack="returnBack" @delete="remove"
                  @actualDelete="actualDelete" :flowType="11"
                  :dataId="(params || {}).id || ((params || {}).handle_param || {}).id"
      ></FlowBtnRow>
    </div>
  </div>
</template>

<script>
import common from '@/utils/common.js'
import { get_seal_type_list } from '@/api/attendance/sael_out_bring'
import FlowBtnRow from '@/components/FlowBtnRow/index'
import { save, begin, remove, return_back, pass, actual_delete, one } from '@/api/attendance/seal_apply'
import { get_company, getDeptCompleteNameById } from '@/api/system/department'
import { getToken } from '@/utils/auth'
import { upFileUrl } from '@/api/others'

export default {
  name: 'seal_apply_details',
  components: {
    FlowBtnRow
  },
  data() {
    return {
      formLoading: false,
      cuRules: {
        seal_type_id: [
          { required: true, message: '请选择印章类型', trigger: 'change' }
        ],
        purpose: [
          { required: true, message: '请输入印章用途', trigger: 'blur' }
        ],
        company_id: [
          { required: true, message: '请选择公司', trigger: 'change' }
        ]
      },
      cuForm: {
        post: null,
        seal_type_id: null,
        seal_type_name: null,
        purpose: null,
        applicant_id: null,
        applicant_name: null,
        applicant_dept_id: null,
        applicant_dept_name: null,
        can_check: false,
        company_id: null,
        useSealFlowAttachmentList: [] // 附件信息
      },
      formDisabled: false,
      sealTypeList: [],
      is_created: false,
      main_dept_name: null,
      companyArr: [],
      params: {},
      uploadHeaders: {},
      upFileUrl,
    }
  },
  async created() {
    if (getToken()) {
      this.uploadHeaders['Authorization'] = getToken()
    }
    // this.initSealTypeList()
    this.initCompany()
	console.log(common.getPageParams()) // 根据路由uuid获取页面参数
    const uuid = this.$route.query.uuid
    const params = this.$store.state.keep.pageParamsMap.get(uuid)
    this.params = params
    if (params.is_created) {
      this.is_created = params.is_created
    }
    if (params.look) {
      this.formLoading = true
      await one({ id: params.id }).then(
        res => {
          this.formLoading = false
          this.cuForm = res.data
          this.cuForm.useSealFlowAttachmentList = this.cuForm.useSealFlowAttachmentList.map(item => {
            return {
              name: item.origin_name,
              origin_name: item.origin_name,
              url: item.url
            }
          })
          this.initSealTypeList()
        }
      )
      this.formDisabled = true
    }
    if (params.handle_param) {
      this.formLoading = true
      await one({ id: params.handle_param.id }).then(
        res => {
          this.formLoading = false
          this.cuForm = res.data
          this.initSealTypeList()
        }
      )
      // 禁用表单
      if (params.handle_param.from == 1 || params.handle_param.from == 2 || params.handle_param.from == 3 || params.handle_param.from == 7) {
        this.formDisabled = true
      }
    }
    if (this.is_created) {
      await this.getDeptCompleteName(this.$store.state.user.mainDeptId)
    } else {
      this.main_dept_name = this.cuForm.applicant_dept_name
    }
  },
  computed: {
    user_name() {
      return this.is_created ? this.$store.state.user.name : this.cuForm.applicant_name
    },
    main_dept_post() {
      return this.is_created ? this.$store.state.user.mainDeptPost : this.cuForm.post
    },
    user_id() {
      return this.$store.state.user.id
    }
  },
  methods: {
    initSealTypeList(flag = false) {
      if (flag) {
        this.cuForm.seal_type_id = null
        this.$nextTick(() => {
          this.$refs['cuForm'].clearValidate()
        })
      }
      this.formLoading = true
      get_seal_type_list({ company_id: this.cuForm.company_id }).then(
        res => {
          this.sealTypeList = res.data
          this.formLoading = false
        }
      ).catch(() => {
        this.formLoading = false
      })
    },
    /**
     * 初始化公司数据
     */
    initCompany() {
      get_company().then(
        res => {
          this.companyArr = res.data
        }
      )
    },
    // 关闭界面
    closePage() {
      this.$store.dispatch('tagsView/closePage', this.$route.name)
    },
    submit() {
      if (this.is_created) {
        const tmp = {
          applicant_id: this.$store.state.user.id,
          applicant_name: this.user_name,
          post: this.main_dept_post,
          applicant_dept_id: this.$store.state.user.mainDeptId,
          applicant_dept_name: this.main_dept_name,
          seal_type_name: this.sealTypeList.find(item => item.id == this.cuForm.seal_type_id).name
        }
        this.cuForm = Object.assign(this.cuForm, tmp)
      }
      const loading = this.$loading({
        lock: true,
        text: '提交中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      begin(this.cuForm).then(
        res => {
          if (res.code == 200) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.closePage()
          } else {
            this.$message.error('操作失败')
          }
          loading.close()
        }
      ).catch(() => {
        this.$message.error('操作失败')
        loading.close()
      })
    },
    save() {
      if (this.is_created) {
        const tmp = {
          applicant_id: this.$store.state.user.id,
          applicant_name: this.user_name,
          post: this.main_dept_post,
          applicant_dept_id: this.$store.state.user.mainDeptId,
          applicant_dept_name: this.main_dept_name,
          seal_type_name: this.sealTypeList.find(item => item.id == this.cuForm.seal_type_id).name
        }
        this.cuForm = Object.assign(this.cuForm, tmp)
      }
      const loading = this.$loading({
        lock: true,
        text: '提交中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      save(this.cuForm).then(
        res => {
          if (res.code == 200) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.closePage()
          } else {
            this.$message.error('操作失败')
          }
          loading.close()
        }
      ).catch(() => {
        this.$message.error('操作失败')
        loading.close()
      })
    },
    pass(opinion) {
      const loading = this.$loading({
        lock: true,
        text: '提交中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      pass({ id: this.cuForm.id, wf_check_opinion: opinion, wf_check_sign_url: '' }).then(res => {
        if (res.code == 200) {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.closePage()
        } else {
          this.$message.error('操作失败')
        }
        loading.close()
      }).catch(() => {
        this.$message.error('操作失败')
        loading.close()
      })
    },
    returnBack(opinion) {
      const loading = this.$loading({
        lock: true,
        text: '提交中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      return_back({ id: this.cuForm.id, wf_check_opinion: opinion, wf_check_sign_url: '' }).then(
        res => {
          if (res.code == 200) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.closePage()
          } else {
            this.$message.error('操作失败')
          }
          loading.close()
        }
      ).catch(() => {
        this.$message.error('操作失败')
        loading.close()
      })
    },
    remove() {
      const loading = this.$loading({
        lock: true,
        text: '提交中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      remove({ id: this.cuForm.id }).then(
        res => {
          if (res.code == 200) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.closePage()
          } else {
            this.$message.error('操作失败')
          }
          loading.close()
        }
      ).catch(() => {
        this.$message.error('操作失败')
        loading.close()
      })
    },
    actualDelete() {
      const loading = this.$loading({
        lock: true,
        text: '提交中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      actual_delete({ id: this.cuForm.id }).then(
        res => {
          if (res.code == 200) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.closePage()
          } else {
            this.$message.error('操作失败')
          }
          loading.close()
        }
      ).catch(() => {
        this.$message.error('操作失败')
        loading.close()
      })
    },
    /**
     * 获取主部门名称
     * @param id 部门ID
     */
    getDeptCompleteName(id) {
      if (id) {
        this.formLoading = true
        getDeptCompleteNameById({ id }).then(
          res => {
            this.main_dept_name = res.data
            this.formLoading = false
          }
        )
      }
    },
    handlePreview(file) {
      window.open(file.url, '_blank')
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    onRemove(file) {
      this.cuForm.useSealFlowAttachmentList = this.cuForm.useSealFlowAttachmentList.filter(item => item.url !== file.url)
    },
    beforeUpload() {
      this.loading = this.$loading({
        lock: true,
        text: '上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    uploadError() {
      this.loading.close()
    },
    uploadSuccess(response, file, fileList) {
      console.log(response, file)
      this.loading.close()
      this.cuForm.useSealFlowAttachmentList.push({
        name: file.name,
        origin_name: file.name,
        url: response.data
      })
    },
  }
}
</script>

<style scoped>
.mailTable {
  width: 80%;
  font-size: 14px;
  margin: 0 auto 10px auto;
  border-collapse: collapse;
}

.mailTable tr td {
  width: 400px;
  height: 60px;
  line-height: 35px;
  box-sizing: border-box;
  padding: 0 10px;
  border-bottom: 1px solid #E6EAEE;
  border-right: 1px solid #E6EAEE;
}

.firstTr td {
  border-top: 1px solid #E6EAEE;
}

.firstTd {
  width: 150px !important;
  border-left: 1px solid #E6EAEE;
}

.mailTable tr td.column {
  text-align: center;
  /*border: 1px solid #8c939d;*/
}

.tip {
  color: red;
}

.header {
  padding-top: 20px;
  text-align: center;
  font-size: 25px;
  font-weight: bold;
  margin: 10px auto;
}

/deep/ .el-form-item__content {
  margin-left: 10px !important;
}

/deep/ .el-radio {
  margin-right: 30px;
}

.title {
  background: #F5F7FA;
  font-weight: bold;
}

/deep/ .el-range-editor.is-disabled input {
  background-color: white;
  color: black;
}

/deep/ .el-radio__input.is-disabled + span.el-radio__label {
  color: black;
}

/deep/ .el-radio__input.is-checked .el-radio__inner {
  border-color: #409EFF;
  background: #409EFF
}

/deep/ .el-radio__input.is-disabled.is-checked .el-radio__inner::after {
  width: 4px;
  height: 4px;
  border-radius: 100%;
  background-color: #FFF;
}

/deep/ .el-textarea.is-disabled .el-textarea__inner {
  background-color: white;
  color: black;
}

/deep/ .el-input.is-disabled .el-input__inner {
  background-color: white;
  color: black;
}

/deep/ .upload_none .el-upload--text {
  display: none;
}
</style>
